package com.able.wanandroid.module;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.able.wanandroid.R;
import com.able.wanandroid.base.BaseActivity;
import com.able.wanandroid.databinding.ActivityMainBinding;
import com.able.wanandroid.module.about.AboutActivity;
import com.able.wanandroid.module.home.HomeFragment;
import com.able.wanandroid.module.hotkey.HotKeyActivity;
import com.able.wanandroid.module.knowledge.KnowledgeListActivity;
import com.able.wanandroid.module.test.TestRxActivity;
import com.able.wanandroid.module.tree.TreeFragment;
import com.able.wanandroid.utils.AppUtils;
import com.able.wanandroid.utils.DownloadManagerUtils;
import com.able.wanandroid.utils.NotificationUtils;
import com.able.wanandroid.utils.ToastUtils;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author Able
 * @date 2018/3/21
 * @description 应用主界面
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> implements View.OnClickListener,
        EasyPermissions.PermissionCallbacks {

    private HomeFragment homeFragment;
    private TreeFragment treeFragment;
    private DownloadManagerUtils mDownloadManagerUtil;
    private String apkUrl = "https://express.360ssb.com/express/api/annex/download?id=216a7f7b391e444b9e113913ab7ef7f9";
    long downloadId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        reqRuntimePermission();

        initView();
        initListener();
        initDrawerToggle();
    }

    private void initView() {
        setTitle("玩Android");
        setNavigationIcon(R.drawable.ic_menu);

        showFragment(1);
        mDownloadManagerUtil = new DownloadManagerUtils(this);
    }

    // 添加菜单动画
    private void initDrawerToggle() {
        // 参数：开启抽屉的activity、DrawerLayout的对象、toolbar按钮打开关闭的对象、描述open drawer、描述close drawer
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mBinding.drawerLayout,
                mBaseBinding.toolBar, R.string.drawer_open, R.string.drawer_close);
        // 添加抽屉按钮，通过点击按钮实现打开和关闭功能; 如果不想要抽屉按钮，只允许在侧边边界拉出侧边栏，可以不写此行代码
        mDrawerToggle.syncState();
        // 设置按钮的动画效果; 如果不想要打开关闭抽屉时的箭头动画效果，可以不写此行代码
        mBinding.drawerLayout.addDrawerListener(mDrawerToggle);
    }

    private void initListener() {
        mBinding.bottomNavigation.setOnNavigationItemSelectedListener(new MyOnBottomNavigationListener());
        mBinding.navigationView.setNavigationItemSelectedListener(new MyOnDrawerNavigationListener());
        // 设置侧滑菜单图标显示本来颜色
        mBinding.navigationView.setItemIconTintList(null);
    }

    /**
     * 添加右上角菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 右上角菜单按钮事件
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuHot) {
            ToastUtils.showToast(this, "Hot");
            Intent intent2Hot = new Intent(MainActivity.this, HotKeyActivity.class);
            startActivity(intent2Hot);
        }
        if (item.getItemId() == R.id.menuSearch) {
            ToastUtils.showToast(this, "Search");
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        mDownloadManagerUtil = new DownloadManagerUtils(this);
    }


    /**
     * 底部导航菜单事件监听
     */
    private class MyOnBottomNavigationListener implements BottomNavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            if (item.getItemId() == R.id.navigation_home) {
                ToastUtils.showSuccess(MainActivity.this, "home");
                showFragment(1);
                return true;
            } else if (item.getItemId() == R.id.navigation_type) {
                ToastUtils.showError(MainActivity.this, "type");
                showFragment(2);
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 侧滑菜单事件监听
     */
    private class MyOnDrawerNavigationListener implements NavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.nav_like:
                    ToastUtils.showError(MainActivity.this, "like");
                    sendNotification();
                    break;
                case R.id.nav_about:
                    Intent intent2About = new Intent(MainActivity.this, AboutActivity.class);
                    startActivity(intent2About);
                    break;
                case R.id.nav_update:
                    ToastUtils.showError(MainActivity.this, "update");
                    if (downloadId != 0) {
                        mDownloadManagerUtil.removeCurrentTask(downloadId);
                    }
                    downloadId = mDownloadManagerUtil.download(apkUrl, "ShiShiBang.apk", "时时帮更新包");
                    break;
                case R.id.nav_knowledge:
                    Intent intent2knowledge = new Intent(MainActivity.this, KnowledgeListActivity.class);
                    startActivity(intent2knowledge);
                    break;
                case R.id.nav_test:
                    Intent intent2rx = new Intent(MainActivity.this, TestRxActivity.class);
                    startActivity(intent2rx);
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    private void sendNotification() {
        NotificationUtils notificationUtils = new NotificationUtils(MainActivity.this);
        notificationUtils
                .setIconId(R.drawable.ic_action_no_like)
                .setTitle("Notification")
                .setContent("适配Android 8.0")
                .setAutoCancel(true)
                .sendNotification();
    }


    /**
     * 显示fragment
     *
     * @param id 导航按钮id
     */
    private void showFragment(int id) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hindFragment(transaction);
        switch (id) {
            case 1:
                if (homeFragment != null) {
                    transaction.show(homeFragment);
                } else {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.content, homeFragment);
                }
                break;
            case 2:
                if (treeFragment != null) {
                    transaction.show(treeFragment);
                } else {
                    treeFragment = new TreeFragment();
                    transaction.add(R.id.content, treeFragment);
                }
                break;
        }
        transaction.commit();
    }

    /**
     * 隐藏fragment
     *
     * @param transaction
     */
    private void hindFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (treeFragment != null) {
            transaction.hide(treeFragment);
        }
    }


    /**
     * 获取动态权限
     */
    private void reqRuntimePermission() {
        String[] runtimePermission = {Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.REQUEST_INSTALL_PACKAGES};
        if (EasyPermissions.hasPermissions(this, runtimePermission)) {
            // 已经申请过权限，做想做的事
        } else {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(this, "没有授予权限将导致某些功能异常", 2, runtimePermission);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // 请求成功执行相应的操作
        switch (requestCode) {
            case 0:
                Toast.makeText(this, "已获取WRITE_EXTERNAL_STORAGE权限", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Toast.makeText(this, "已获取WRITE_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // 请求失败，执行相应操作
        ToastUtils.showError(this, "请求权限失败");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        switch (requestCode) {
            case 10011:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    AppUtils.installAPP(MainActivity.this);
                } else {
                    ToastUtils.showInfo(MainActivity.this, "请允许该程序安装更新！");
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, 10012);
                }
                break;
        }
    }

}
